package com.tceasy.gateway.api;

import com.tceasy.common.utils.id.IdBuilder;
import com.tceasy.gateway.util.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import static com.tceasy.gateway.api.RequestParamUtil.*;

/**
 *Created by zhanghuan on 2016/4/10.
 */
public class GatewayServlet extends HttpServlet {

    private static final Logger logger= LoggerFactory.getLogger(GatewayServlet.class);

    private RequestDispatcher requestDispatcher;

    @Override
    public void init() throws ServletException {
        requestDispatcher= SpringUtils.getBean(RequestDispatcher.class);
    }

    /**doGet方法*/
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**doPost方法*/
    public void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
            throws ServletException, IOException {
        long startTime = System.currentTimeMillis();
        Response result=null;
        try{
            MDC.put("logId",IdBuilder.getID());
            result= processRequest(httpRequest);
        }catch (Exception e){
            logger.error(e.getMessage());
            result=Response.fail(e.getMessage());
        }finally {
            response(httpResponse,result.toJson());
            long endTime=System.currentTimeMillis();
            logger.info("请求时长：{}",endTime-startTime);
            MDC.clear();
        }
    }


    /**执行请求方法*/
    private Response processRequest(HttpServletRequest request){
        String param = getParam(request);
        String header=getHearders(request);
        String remoteIp=getRemoteIp(request);
        logger.info("=========param:{},headers:{}",param,header);
        /*解析校验验签等等*/
        Map reqJson=parseParam(param);
        reqJson.put("remoteIp",remoteIp);
        String requestId= (String) reqJson.get("requestId");
        /*若没传requestId,则用logId作为requestId*/
        if(StringUtils.isBlank(requestId)){
            reqJson.put("requestId",MDC.get("logId"));
        }
        return  requestDispatcher.dispatch(reqJson);
    }


    /**组装返回参数*/
    private void response(HttpServletResponse httpResponse, String result) throws IOException {
        logger.info("response:{}", result);
        httpResponse.setHeader("Pragma", "no-cache");
        httpResponse.setCharacterEncoding("utf-8");
        httpResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter out = httpResponse.getWriter();
        out.print(result);
        out.flush();
        out.close();
    }



}
